import sys
import os
import logging
import re
import json
from typing import Dict, List, Any, Optional, Tuple

# 添加项目根路径到 sys.path
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))

# 导入 MySQLUtil
from shared.utils.MySQLUtil import MySQLUtil

# 设置日志
logger = logging.getLogger(__name__)

def get_各学历及总体_就业单位分布(
    project_id: int,
    questionnaire_ids: List[int],
    product_code: Optional[str] = None,
    project_code: Optional[str] = None,
    region_code: Optional[str] = None,
    education: Optional[str] = None
) -> Dict[str, Any]:
    """
    各学历及总体，就业单位分布 - 指标计算函数
    
    ## 指标说明
    本指标用于统计各学历层次及总体毕业生就业单位性质的分布情况，计算各类型单位就业人数占总就业人数的比例。
    数据来源于学生客观表，筛选条件为：毕业去向不为待就业和暂不就业，且单位性质字段不为空。
    计算结果按单位性质分组展示，并计算各自占比。
    
    ## Args
        project_id (int): 项目ID，用于查询项目配置信息
        questionnaire_ids (List[int]): 问卷ID集合，用于确定数据范围
        product_code (Optional[str]): 产品编码，用于路由到特定计算逻辑
        project_code (Optional[str]): 项目编码，用于路由到特定计算逻辑
        region_code (Optional[str]): 区域编码，用于路由到特定计算逻辑
        education (Optional[str]): 学历层次，可选值：本科毕业生/专科毕业生/硕士研究生/博士研究生
    
    ## 示例
    ### 输入
    ```json
    {
        "project_id": 5895,
        "questionnaire_ids": [11158, 11159]
    }
    ```
    
    ### 输出
    ```json
    {
        "success": true,
        "message": "ok",
        "code": 0,
        "result": [
            {
                "group": "本科毕业生",
                "data": [
                    {
                        "company_nature": "国有企业",
                        "count": 120,
                        "ratio": 0.35
                    },
                    {
                        "company_nature": "民营企业",
                        "count": 150,
                        "ratio": 0.44
                    }
                ]
            },
            {
                "group": "总体",
                "data": [
                    {
                        "company_nature": "国有企业",
                        "count": 320,
                        "ratio": 0.30
                    },
                    {
                        "company_nature": "民营企业",
                        "count": 450,
                        "ratio": 0.42
                    }
                ]
            }
        ]
    }
    ```
    """
    logger.info(f"开始计算指标: 各学历及总体，就业单位分布, 项目ID: {project_id}")
    
    try:
        db = MySQLUtil()  

        # 1. 查询项目配置信息
        project_sql = """
        SELECT client_code, item_year 
        FROM client_item 
        WHERE id = %s
        """
        project_info = db.fetchone(project_sql, (project_id,))
        if not project_info:
            raise ValueError(f"未找到项目ID={project_id}的配置信息")

        client_code = project_info['client_code']
        item_year = project_info['item_year']
        
        logger.info(f"项目配置: client_code={client_code}, item_year={item_year}")

        # 2. 计算 shard_tb_key
        shard_tb_key = re.sub(r'^[A-Za-z]*0*', '', client_code)
        logger.info(f"计算得到 shard_tb_key: {shard_tb_key}")

        # 3. 构建结果容器
        result_data = []
        education_list = ['本科毕业生', '专科毕业生', '硕士研究生', '博士研究生']
        
        # 4. 按学历计算
        if education:
            education_list = [education]
            
        for edu in education_list:
            # 计算特定学历的就业单位分布
            sql = f"""
            SELECT 
                company_nature, 
                count(*) as count, 
                count(*)/(
                    SELECT count(*) 
                    FROM dim_client_target_baseinfo_student_calc_{item_year} 
                    WHERE shard_tb_key = %s 
                    AND grad_dest_merge NOT IN ('待就业', '暂不就业') 
                    AND company_nature != '' 
                    AND education = %s
                ) AS ratio
            FROM dim_client_target_baseinfo_student_calc_{item_year}
            WHERE 
                shard_tb_key = %s
                AND grad_dest_merge NOT IN ('待就业', '暂不就业')
                AND company_nature != ''
                AND education = %s
            GROUP BY company_nature
            ORDER BY count DESC
            """
            params = (shard_tb_key, edu, shard_tb_key, edu)
            edu_results = db.fetchall(sql, params)
            
            if edu_results:
                result_data.append({
                    "group": edu,
                    "data": [
                        {
                            "company_nature": row['company_nature'],
                            "count": row['count'],
                            "ratio": float(row['ratio']) if row['ratio'] else 0.0
                        } for row in edu_results
                    ]
                })

        # 5. 计算总体就业单位分布
        total_sql = f"""
        SELECT 
            company_nature, 
            count(*) as count, 
            count(*)/(
                SELECT count(*) 
                FROM dim_client_target_baseinfo_student_calc_{item_year} 
                WHERE shard_tb_key = %s 
                AND grad_dest_merge NOT IN ('待就业', '暂不就业') 
                AND company_nature != ''
            ) AS ratio
        FROM dim_client_target_baseinfo_student_calc_{item_year}
        WHERE 
            shard_tb_key = %s
            AND grad_dest_merge NOT IN ('待就业', '暂不就业')
            AND company_nature != ''
        GROUP BY company_nature
        ORDER BY count DESC
        """
        total_params = (shard_tb_key, shard_tb_key)
        total_results = db.fetchall(total_sql, total_params)
        
        if total_results:
            result_data.append({
                "group": "总体",
                "data": [
                    {
                        "company_nature": row['company_nature'],
                        "count": row['count'],
                        "ratio": float(row['ratio']) if row['ratio'] else 0.0
                    } for row in total_results
                ]
            })

        logger.info(f"指标 '各学历及总体，就业单位分布' 计算成功")
        return {
            "success": True,
            "message": "ok",
            "code": 0,
            "result": result_data
        }

    except Exception as e:
        logger.error(f"计算指标 '各学历及总体，就业单位分布' 时发生错误: {str(e)}", exc_info=True)
        return {
            "success": False,
            "message": f"数据获取失败: 各学历及总体，就业单位分布",
            "code": 500,
            "error": str(e)
        }